package com.atguigu.controller;

import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import com.atguigu.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Jia Fa
 * @create 2021-10-09 0:24
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/findAll")
    public Result findAll() {
        try {
            //先从缓存查询
            List<User> userList = (List<User>) redisTemplate.boundValueOps("userList").get();
            System.out.println("Redis 中查询获得");
            if (userList == null) {
                userList = (List<User>) userService.findAll();
                //若未从Redis中查询到则添加到缓存
                System.out.println("持久层查询获得");
                redisTemplate.boundValueOps("userList").set(userList);
            }
            return Result.ok(userList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败！");
        }
    }

    @RequestMapping("/add")
    public Result add(User user) {
        return Result.ok(userService.add(user));
    }

    @RequestMapping("/edit")
    public Result edit(User user) {
        return Result.ok(userService.edit(user));
    }

    @RequestMapping("/delete")
    public Result deleteById(Integer id) {
        return Result.ok(userService.deleteById(id));
    }
}
